package com.itheima.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @program: itheima-jdk8
 * @description:
 * @author: zhanghz001
 * @create: 2021-01-08 15:57
 **/
public class WhenCompleteDemo1 {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        // CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
        //     try {
        //         Thread.sleep(3000);
        //     } catch (InterruptedException e) {
        //         e.printStackTrace();
        //     }
        //     System.out.println("111" + Thread.currentThread().getName());
        // }, pool);
        // System.out.println("主线程结束");
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            
            System.out.println("222:" + Thread.currentThread().getName());
            int i = 1 / 0;
            return 123;
        }, pool);
        
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            
            //子任务
            try {
                System.out.println(Thread.currentThread().getName());
                int i = 1 / 0;
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            return 123;
        }, pool);
        
        future.exceptionally((t) -> {
            System.out.println("异常结果处理的线程0：" + Thread.currentThread().getName());
            return null;
        });
        // System.out.println("主线程结束2"); 
        //
        System.out.println("main:" + Thread.currentThread().getName());
        
        future1.exceptionally(throwable -> {
            System.out.println(throwable.getMessage());
            System.out.println("异常结果触发任务线程222:" + Thread.currentThread().getName());
            pool.shutdown();
            return null;
        });
    }
}
